package me.wangqu.weiyouqu.web.rest;

import com.codahale.metrics.annotation.Timed;
import me.wangqu.weiyouqu.security.SecurityUtils;
import me.wangqu.weiyouqu.web.rest.business.model.RefererModel;
import me.wangqu.weiyouqu.web.rest.business.service.ArticleService;
import me.wangqu.weiyouqu.web.rest.business.service.SignService;
import me.wangqu.weiyouqu.web.rest.util.AccountUtil;
import me.wangqu.weiyouqu.web.rest.util.HttpUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.net.URISyntaxException;

/**
 * REST controller for managing SignIn.
 */
@RestController
@RequestMapping("/api")
public class SignInResource {

    private final Logger log = LoggerFactory.getLogger(SignInResource.class);
    @Autowired
    private SignService signService;

    @RequestMapping(value = "/sign/self",
        method = RequestMethod.GET,
        produces = { MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_JSON_VALUE })
    @Timed
    public ResponseEntity<String> getSelfSignIn() {
        log.debug("REST request to get self SignIn");
        // 判断今天是否可以签到
        boolean isSign = signService.isSign(SecurityUtils.getCurrentUserLogin());

        return isSign ? ResponseEntity.ok().body(null) : ResponseEntity.badRequest().body(null);
    }

    /**
     * 签到
     * @return
     * @throws URISyntaxException
     */
    @RequestMapping(value = "/sign/self",
        method = RequestMethod.POST,
        produces = { MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_JSON_VALUE })
    @Timed
    @Transactional
    public ResponseEntity<?> selfSignIn(HttpServletRequest request) throws URISyntaxException {
        log.debug("REST request to save sef SignIn");
        // 判断今天是否可以签到
        String login = SecurityUtils.getCurrentUserLogin();
        boolean sign = signService.isSign(login);
        if (sign) {
            // 签到操作
            BigDecimal amount = AccountUtil.signIncome();
            if (signService.sign(login, amount, HttpUtil.getClientIP(request))) {
                return ResponseEntity.ok(String.valueOf(amount));
            } else {
                return ResponseEntity.badRequest().body("签到失败");
            }
        } else {
            return ResponseEntity.badRequest().body("请勿重复签到");
        }
    }

}
